using micromsg;
using MicroMsg.Common.Event;
using MicroMsg.Common.Timer;
using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Network;
using MicroMsg.Storage;
using System;
using System.Xml.Linq;
namespace MicroMsg.Scene.Voice
{
	public class DownloadVoiceService
	{
		private const string TAG = "DownloadVoiceService";
		private static TimerObject mTimerObject;
		private static EventWatcher mWatcher;
		private static bool isFirstSync;
		private static bool isAppActive;
		public DownloadVoiceService()
		{
			DownloadVoiceService.mWatcher = new EventWatcher(this, null, new EventHandlerDelegate(DownloadVoiceService.HandlerDoScene));
			EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_SYNC, DownloadVoiceService.mWatcher);
			EventCenter.registerEventWatcher(EventConst.ON_NET_DEVICE_CONNECTED, DownloadVoiceService.mWatcher);
			EventCenter.registerEventWatcher(EventConst.ON_APP_ACTIVE, DownloadVoiceService.mWatcher);
		}
		private static void HandlerDoScene(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			if (evtArgs == null)
			{
				return;
			}
			Log.smethod_4("DownloadVoiceService", "onHander NetSceneNewSync mEventID = " + evtArgs.mEventID);
			if (evtArgs.mEventID == EventConst.ON_NET_DEVICE_CONNECTED)
			{
				DownloadVoiceService.doSceneBegin();
				return;
			}
			if (evtArgs.mEventID == EventConst.ON_APP_ACTIVE)
			{
				DownloadVoiceService.isAppActive = true;
				return;
			}
			NetSceneSyncResult netSceneSyncResult = evtArgs.mObject as NetSceneSyncResult;
			if (netSceneSyncResult == null)
			{
				Log.smethod_1("DownloadVoiceService", "NetSceneSyncResult == null");
				return;
			}
			if (netSceneSyncResult.syncStatus == SyncStatus.syncEnd && netSceneSyncResult.syncCount == 0)
			{
				Log.smethod_5("DownloadVoiceService", string.Concat(new object[]
				{
					"onHander sync event result.syncStatus = ",
					netSceneSyncResult.syncStatus,
					" result.syncCount = ",
					netSceneSyncResult.syncCount,
					" DownloadVoiceService doSceneBegin"
				}));
				ServiceCenter.sceneNewSync.setRecvMsgStatus(RecvMsgStatus.isRecvVoice);
				DownloadVoiceService.isFirstSync = true;
				DownloadVoiceService.doSceneBegin();
				return;
			}
			if (netSceneSyncResult.syncStatus == SyncStatus.syncEnd && DownloadVoiceService.isAppActive)
			{
				Log.smethod_5("DownloadVoiceService", string.Concat(new object[]
				{
					"onHander sync event result.syncStatus = ",
					netSceneSyncResult.syncStatus,
					" result.syncCount = ",
					netSceneSyncResult.syncCount,
					" isAppActive = ",
					DownloadVoiceService.isAppActive,
					" DownloadVoiceService doSceneBegin"
				}));
				ServiceCenter.sceneNewSync.setRecvMsgStatus(RecvMsgStatus.isRecvVoice);
				DownloadVoiceService.doSceneBegin();
				return;
			}
			Log.smethod_5("DownloadVoiceService", string.Concat(new object[]
			{
				"onHander sync event result.syncStatus = ",
				netSceneSyncResult.syncStatus,
				" result.syncCount = ",
				netSceneSyncResult.syncCount
			}));
		}
		public static void doSceneBegin()
		{
			DownloadVoiceService.checkReadyContextDispatcher();
			DownloadVoiceService.onVoiceContextDispatcher(null, null);
		}
		public static void onVoiceContextDispatcher(object sender, EventArgs e)
		{
			DownloadVoiceContextMgr.getInstance().clearnFinishedContext();
			if (DownloadVoiceContextMgr.getInstance().getCount() <= 0)
			{
				DownloadVoiceStorage.loadDownloadVoiceContextList();
			}
			if (DownloadVoiceContextMgr.getInstance().getCount() <= 0)
			{
				Log.smethod_4("DownloadVoiceService", "all ready, close dispatcher timer. ");
				if (DownloadVoiceService.isFirstSync)
				{
					ServiceCenter.sceneNewSync.unsetRecvMsgStatus(RecvMsgStatus.isRecvVoice);
					EventCenter.postEvent(EventConst.ON_NETSCENE_DOWNLOADVOICE_SERVICE_FINISH, null, null);
					DownloadVoiceService.isFirstSync = false;
				}
				if (DownloadVoiceService.isAppActive)
				{
					ServiceCenter.sceneNewSync.unsetRecvMsgStatus(RecvMsgStatus.isRecvVoice);
					EventCenter.postEvent(EventConst.ON_NETSCENE_DOWNLOADVOICE_SERVICE_FINISH, null, null);
					DownloadVoiceService.isAppActive = false;
				}
				if (DownloadVoiceService.mTimerObject != null)
				{
					DownloadVoiceService.mTimerObject.stop();
					DownloadVoiceService.mTimerObject = null;
				}
				return;
			}
			int num = DownloadVoiceContextMgr.getInstance().countRunningContext();
			int downloadPackNum = (int)DownloadVoiceService.getDownloadPackNum();
			if (num >= downloadPackNum)
			{
				Log.smethod_4("DownloadVoiceService", "return request, because reach MaxRunningNum = " + downloadPackNum);
				return;
			}
			for (int i = 0; i < downloadPackNum - num; i++)
			{
				DownloadVoiceContext firstContextNeedHandle = DownloadVoiceContextMgr.getInstance().getFirstContextNeedHandle();
				if (firstContextNeedHandle == null)
				{
					return;
				}
				Log.smethod_4("DownloadVoiceService", "new task startup, mMsgSvrID = " + firstContextNeedHandle.mMsgSvrID);
				NetSceneDownloadVoice netSceneDownloadVoice = new NetSceneDownloadVoice();
				netSceneDownloadVoice.mOnSceneFinished += new onSceneDownloadFinishedDelegate(DownloadVoiceService.onSceneFinished);
				netSceneDownloadVoice.doScene(firstContextNeedHandle);
			}
		}
		private static void onSceneFinished(DownloadVoiceContext context)
		{
			if (context.mStatus == 4)
			{
				Log.smethod_4("DownloadVoiceService", "download voice completed, mMsgSvrID = " + context.mMsgSvrID);
				DownloadVoiceStorage.updateVoiceMsgStatus(context.strTalker, context.mMsgSvrID, MsgUIStatus.Success);
				EventCenter.postEvent(EventConst.ON_NETSCENE_DOWNLOADVOICE_SUCCESS, null, null);
				return;
			}
			if (context.mStatus == 5)
			{
				Log.smethod_4("DownloadVoiceService", "download voice error, mMsgSvrID = " + context.mMsgSvrID);
				DownloadVoiceStorage.updateVoiceMsgStatus(context.strTalker, context.mMsgSvrID, MsgUIStatus.Fail);
				EventCenter.postEvent(EventConst.ON_NETSCENE_DOWNLOADVOICE_ERR, null, null);
				return;
			}
			Log.smethod_1("DownloadVoiceService", "download voice status error, mMsgSvrID = " + context.mMsgSvrID);
		}
		private static void checkReadyContextDispatcher()
		{
			if (DownloadVoiceService.mTimerObject == null)
			{
				Log.smethod_5("DownloadVoiceService", "download voice service dispatcher startup. ");
				DownloadVoiceService.mTimerObject = TimerService.addTimer(1, new EventHandler(DownloadVoiceService.onVoiceContextDispatcher), 1, -1);
				DownloadVoiceService.mTimerObject.start();
			}
		}
		public static bool reDownloadVoiceInfo(ChatMsg chatMsg_0)
		{
			MsgTrans msgTrans = new MsgTrans();
			msgTrans.nTransType = 4;
			msgTrans.nStatus = 0;
			msgTrans.strToUserName = AccountMgr.getCurAccount().strUsrName;
			msgTrans.strFromUserName = chatMsg_0.strTalker;
			string text = chatMsg_0.strMsg;
			if (ContactMgr.getUserType(chatMsg_0.strTalker) == ContactMgr.UserType.UserTypeChatRoom)
			{
				text = text.Substring(text.IndexOf('\n') + 1);
			}
			if (!DownloadVoiceService.parseVoiceMsgXML(text, msgTrans))
			{
				Log.smethod_5("DownloadVoiceService", "parseVoiceMsgXML failed");
				return false;
			}
			msgTrans.nMsgSvrID = chatMsg_0.nMsgSvrID;
			if (AccountMgr.getCurAccount().strUsrName == msgTrans.strFromUserName)
			{
				Log.smethod_5("DownloadVoiceService", "the mVoiceinfo.strFromUserName is yourself");
				return false;
			}
			DownloadVoiceContext downloadVoiceContext = DownloadVoiceContextMgr.getInstance().GetBySvrID(chatMsg_0.nMsgSvrID);
			if (downloadVoiceContext != null)
			{
				return true;
			}
			downloadVoiceContext = new DownloadVoiceContext(chatMsg_0.nMsgSvrID, chatMsg_0.strTalker);
			downloadVoiceContext.mStatus = 0;
			downloadVoiceContext.Enqueue(msgTrans);
			DownloadVoiceContextMgr.getInstance().putToTail(downloadVoiceContext);
			DownloadVoiceStorage.updateDownloadVoiceContext(msgTrans);
			DownloadVoiceService.doSceneBegin();
			return true;
		}
		public static bool downloadVoiceInfo(AddMsg cmdAM)
		{
			MsgTrans msgTrans = new MsgTrans();
			msgTrans.nTransType = 4;
			msgTrans.nStatus = 0;
			msgTrans.strToUserName = cmdAM.ToUserName.String;
			msgTrans.strFromUserName = cmdAM.FromUserName.String;
			string text = cmdAM.Content.String;
			if (ContactMgr.getUserType(cmdAM.FromUserName.String) == ContactMgr.UserType.UserTypeChatRoom)
			{
				text = text.Substring(text.IndexOf('\n') + 1);
			}
			if (!DownloadVoiceService.parseVoiceMsgXML(text, msgTrans))
			{
				Log.smethod_5("DownloadVoiceService", "parseVoiceMsgXML failed");
				return false;
			}
			msgTrans.nMsgSvrID = cmdAM.MsgId;
			if (AccountMgr.getCurAccount().strUsrName == msgTrans.strFromUserName)
			{
				Log.smethod_5("DownloadVoiceService", "the mVoiceinfo.strFromUserName is yourself");
				return false;
			}
			if (DownloadVoiceService.isCancelVoiceMsg(text))
			{
				Log.smethod_5("DownloadVoiceService", "the msg has been canceled");
				StorageMgr.chatMsg.delMsg(ChatMsgHelper.getTalker(msgTrans.strToUserName, msgTrans.strFromUserName), msgTrans.nMsgSvrID);
				msgTrans.nStatus = 5;
				DownloadVoiceStorage.updateDownloadVoiceContext(msgTrans);
				DownloadVoiceContext bySvrID = DownloadVoiceContextMgr.getInstance().GetBySvrID(cmdAM.MsgId);
				if (bySvrID != null)
				{
					bySvrID.mStatus = 5;
				}
				return false;
			}
			if (cmdAM.ImgBuf != null && cmdAM.ImgBuf.Buffer.Length != 0)
			{
				return DownloadVoiceService.saveShortVoiceInfo(msgTrans, cmdAM.ImgBuf.Buffer.ToByteArray());
			}
			DownloadVoiceContext downloadVoiceContext = DownloadVoiceContextMgr.getInstance().GetBySvrID(cmdAM.MsgId);
			if (downloadVoiceContext == null)
			{
				downloadVoiceContext = new DownloadVoiceContext(cmdAM.MsgId, ChatMsgHelper.getTalker(cmdAM.ToUserName.String, cmdAM.FromUserName.String));
				downloadVoiceContext.mStatus = 0;
				downloadVoiceContext.Enqueue(msgTrans);
				DownloadVoiceContextMgr.getInstance().putToTail(downloadVoiceContext);
			}
			else
			{
				downloadVoiceContext.Enqueue(msgTrans);
			}
			DownloadVoiceStorage.updateDownloadVoiceContext(msgTrans);
			DownloadVoiceService.doSceneBegin();
			return true;
		}
		private static bool saveShortVoiceInfo(MsgTrans voiceinfo, byte[] voiceBuf)
		{
			Log.smethod_5("DownloadVoiceService", "saveShortVoiceInfo in");
			voiceinfo.nStatus = 4;
			DownloadVoiceStorage.updateDownloadVoiceContext(voiceinfo);
			DownloadVoiceStorage.updateVoiceMsgStatus(ChatMsgHelper.getTalker(voiceinfo.strToUserName, voiceinfo.strFromUserName), voiceinfo.nMsgSvrID, MsgUIStatus.Success);
			return StorageMgr.msgVoice.saveVoiceBlockData(voiceinfo, voiceBuf, null);
		}
		public static bool parseVoiceMsgXML(string xmlStr, MsgTrans voiceinfo)
		{
			if (!string.IsNullOrEmpty(xmlStr) && voiceinfo != null)
			{
				bool result;
				try
				{
					XDocument xDocument = XDocument.Parse(xmlStr);
					XElement xElement = xDocument.Element("msg").Element("voicemsg");
					XAttribute xAttribute = xElement.Attribute("clientmsgid");
					if (xAttribute != null)
					{
						voiceinfo.strClientMsgId = xAttribute.get_Value();
					}
					xAttribute = xElement.Attribute("length");
					if (xAttribute != null)
					{
						voiceinfo.nTotalDataLen = int.Parse(xAttribute.get_Value());
					}
					xAttribute = xElement.Attribute("endflag");
					if (xAttribute != null)
					{
						voiceinfo.nEndFlag = int.Parse(xAttribute.get_Value());
					}
					xAttribute = xElement.Attribute("voicelength");
					if (xAttribute != null)
					{
						voiceinfo.nDuration = int.Parse(xAttribute.get_Value());
					}
					return true;
				}
				catch (Exception ex)
				{
					Log.smethod_5("DownloadVoiceService", ex.get_Message());
					result = false;
				}
				return result;
			}
			Log.smethod_5("DownloadVoiceService", "parseVoiceMsgXML, input invalid para");
			return false;
		}
		public static bool isCancelVoiceMsg(string xmlStr)
		{
			if (string.IsNullOrEmpty(xmlStr))
			{
				Log.smethod_5("DownloadVoiceService", "parseVoiceMsgXML, input invalid para");
				return false;
			}
			try
			{
				XDocument xDocument = XDocument.Parse(xmlStr);
				XElement xElement = xDocument.Element("msg").Element("voicemsg");
				XAttribute xAttribute = xElement.Attribute("cancelflag");
				if (xAttribute != null)
				{
					bool result = int.Parse(xAttribute.get_Value()) != 0;
					return result;
				}
			}
			catch (Exception ex)
			{
				Log.smethod_5("DownloadVoiceService", ex.get_Message());
				bool result = false;
				return result;
			}
			return false;
		}
		public static DownloadPackNum getDownloadPackNum()
		{
			if (NetworkDeviceWatcher.isCurrentWifi())
			{
				return DownloadPackNum.NETWORK_WIFI_NUM;
			}
			if (NetworkDeviceWatcher.isCurrentCell3G())
			{
				return DownloadPackNum.NETWORK_3G_NUM;
			}
			if (NetworkDeviceWatcher.isCurrentCell2G())
			{
				return DownloadPackNum.NETWORK_2G_NUM;
			}
			return DownloadPackNum.NETWORK_3G_NUM;
		}
	}
}
